package com.hw.core.system.service;

import com.hw.core.system.entity.Role;
import com.hw.core.system.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(readOnly = true)//全部方法只读事务
@CacheConfig(cacheNames = "roles")
@Service
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;

    @Cacheable(key = "'list'")
    public List<Role> findAll() {
        return roleRepository.findAll();
    }

    @Transactional
    @CacheEvict(allEntries = true)
    public void delete(Integer id) {

        roleRepository.delete( id );


    }

    @Transactional
    @CacheEvict(allEntries = true)
    public Role add(Role role) {
        return roleRepository.save( role );
    }

    @Transactional
    @CacheEvict(allEntries = true)
    public void update(Role role) {
        Role one = roleRepository.findOne( role.getId() );
        one.setPermissions( role.getPermissions() );
        one.setName( role.getName() );
    }

    @Cacheable(key = "#id+'obj'")
    public Role getRoleById(Integer id) {
        return roleRepository.findOne( id );
    }
}
